package com.fuhao.member.service;

import com.fuhao.core.Constants.Constants;
import com.fuhao.core.base.BaseApiService;
import com.fuhao.core.base.BaseResponse;
import com.fuhao.core.transaction.RedisDataSoureceTransaction;
import com.fuhao.core.utils.GenerateToken;
import com.fuhao.dto.input.MemberLoginInpDTO;
import com.fuhao.member.entity.MemberEntity;
import com.fuhao.member.entity.MemberTokenEntity;
import com.fuhao.member.mapper.UserMapper;
import com.fuhao.member.mapper.UserTokenMapper;
import com.fuhao.member.utils.TokenUniqueUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

@RestController
public class QQAuthoriServiceImpl extends BaseApiService<JSONObject> implements QQAuthoriService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private TokenUniqueUtils tokenUniqueUtils;


	@Transactional
	@Override
	public BaseResponse<JSONObject> findByOpenId(MemberLoginInpDTO memberLoginInpDTO) {
		// 1.根据qqOpenId查询用户信息
		String qqOpenId = memberLoginInpDTO.getQqOpenId();
		if (StringUtils.isEmpty(qqOpenId)) {
			return setResultError("qqOpenId不能为空!");
		}
		// 2.如果没有查询到 直接返回状态码203
		MemberEntity memberEntity = userMapper.findByOpenId(qqOpenId);
		if (memberEntity == null) {
			return setResultError(Constants.HTTP_RES_CODE_NOTUSER_203, "根据qqOpenId没有查询到用户信息");
		}
		String loginType = memberLoginInpDTO.getLoginType();
		if (org.apache.commons.lang3.StringUtils.isEmpty(loginType)) {
			return setResultError("登陆类型不能为空!");
		}
		//登录类型仅限于PC、IOS、Android
		if (!(loginType.equals(Constants.MEMBER_LOGIN_TYPE_ANDROID) || loginType.equals(Constants.MEMBER_LOGIN_TYPE_IOS)
				|| loginType.equals(Constants.MEMBER_LOGIN_TYPE_PC))) {
			return setResultError("登陆类型出现错误!");
		}
		// 设备信息
		String deviceInfor = memberLoginInpDTO.getDeviceInfor();
		if (org.apache.commons.lang3.StringUtils.isEmpty(deviceInfor)) {
			return setResultError("设备信息不能为空!");
		}
		//3.创建token，并保持唯一登录
		return tokenUniqueUtils.CheckTokenUnique(memberEntity,memberLoginInpDTO);
	}
}
